﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace USElections.Tiles
{
    public partial class CounterFrontTile : UserControl
    {
        private DispatcherTimer timer;

        public CounterFrontTile()
        {
            InitializeComponent();

            this.StartCountdown();
        }

        private void StartCountdown()
        {
            if (this.timer == null)
            {
                this.timer = new DispatcherTimer();
                this.timer.Interval = TimeSpan.FromMilliseconds(500);
                this.timer.Tick += this.timer_Tick;
                this.timer.Start();
            }
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            DateTime electionDay = new DateTime(2012, 11, 6);
            DateTime currentDateTime = DateTime.Now;

            if (currentDateTime < electionDay)
            {
                TimeSpan diff = electionDay.Subtract(DateTime.Now);

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    this.daysTxt.Text = string.Format("{0} days", diff.Days);
                    this.hoursTxt.Text = string.Format("{0:00}:{1:00}:{2:00}", diff.Hours, diff.Minutes, diff.Seconds);
                });
            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    this.daysTxt.Text = "--";
                    this.hoursTxt.Text = "--";
                });
            }
        }
    }
}
